package com.gq.sherlockhomes;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.gq.bean.StoryItem;

public class XMLParser {
	
	private InputStream is;
	
	public XMLParser(InputStream is) {
		this.is = is;
	}
	
	public InputStream getInputStream() {
		return is;
	}
	
	public ArrayList<StoryItem> parse() {
		ArrayList<StoryItem> result = new ArrayList<StoryItem>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(getInputStream());
			org.w3c.dom.Element root = dom.getDocumentElement();
			NodeList items = root.getElementsByTagName("item");
			for(int i=0;i<items.getLength();i++) {
				Node item = items.item(i);
				StoryItem sitem = new StoryItem();
				String itemName = item.getFirstChild().getTextContent();
				if (itemName.trim().equals("")) continue;
				sitem.setName(itemName);
				sitem.setFilename(item.getLastChild().getTextContent());
				result.add(sitem);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
